/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/7/21 21:55
 * @Description: TODO
 */
public class getIntersectionNode {
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA = getLengthOfListNode(headA);
        int lengthB = getLengthOfListNode(headB);
        ListNode p1 = lengthA > lengthB ? headA : headB;
        ListNode p2 = lengthA > lengthB ? headB : headA;
        int sub = Math.abs(lengthA - lengthB);
        while (sub > 0) {
            p1 = p1.next;
            sub--;
        }
        while (p1 != p2 && p1 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        if (p1 == null) {
            return null;
        }
        return p1;
    }

    private static int getLengthOfListNode(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }

    public static void main(String[] args) {
        int[] nums1 = {2, 6, 4};
        int[] nums2 = {1, 5};
        ListNode headA = ListNode.makeListNode(nums1);
        ListNode headB = ListNode.makeListNode(nums2);
        ListNode node = getIntersectionNode(headA, headB);
        System.out.println(node == null ? null : node.val);
    }
}